<!--
 * @Date: 2023-09-18 19:30:19
 * @LastEditTime: 2023-10-08 15:52:33
 * 介绍:
-->
<script lang="ts" setup>
import { ApiTaskDetails } from "@@/api/wk/index";
import useBalanceStore from "@@/store/useBalanceStore";
import { fixedDecimals } from "@@/utils/tools/format";
import { apiOrderTask, apiOrderTaskRePlay } from "@@/api/wk/index";
import { WkTaskStatus } from "@@/enum/globalEnum";
import useTabPageStore from "@@/store/useTabPageStore";
import { useRactionSheetRef } from "@@/components/rework/RactionSheet/index";
import { _require } from "@@/utils/tools";
import { chain, divide } from "mathjs";
import { toast } from "@@/hooks/vantHooks";
import { sdkWkTransfer } from "@@/sdk/web3Eth";

const tabPageStore = useTabPageStore();
const { homeData } = storeToRefs(tabPageStore);

const balanceStore = useBalanceStore();
const WKC = computed(() => balanceStore.getCoinByCode("WKC"));

const RactionSheetRef = useRactionSheetRef();
const props = defineProps<{
  details: ApiTaskDetails.Data;
}>();
const { t } = useI18n();
/**是上次支付失败，二次支付！ */
const isPlayFailed = computed(
  () => props.details.task_order.status === WkTaskStatus.FAIL
);
async function open() {
  btnLoading.open = true;
  const [apiRes] = await Promise.all([
    tabPageStore.getHomeData(),
    balanceStore.findBalance(WKC.value),
  ]);
  btnLoading.open = false;
  if (!apiRes) return;
  RactionSheetRef.value?.open({
    title: t("jie-dan-zhi-fu"),
  });
}
const emit = defineEmits<{
  (e: "orderTaskSuccess"): void;
}>();

const btnLoading = reactive({
  approve: false,
  orderTask: false,
  open: false,
});
// async function approve() {
//   btnLoading.approve = true;
//   await balanceStore.approve(
//     WKC.value!,
//     undefined,
//     homeData.value?.config_address!
//   );
//   btnLoading.approve = false;
// }
// const isApprove = computed(
//   () => !balanceStore.checkApprove(WKC.value!, amount.value!, address.value!)
// );

async function orderTask() {
  if (!RactionSheetRef.value) return;
  btnLoading.orderTask = true;
  toast.loading(t("jiao-yi-zhong-qing-bu-yao-tui-chu"));
  const payRes = await sdkWkTransfer(
    WKC.value?.contract_addr!,
    amount.value!,
    WKC.value?.format!,
    homeData.value?.address.safe_address!
  );
  btnLoading.orderTask = false;
  toast.close();
  if (!payRes.status) return;
  btnLoading.orderTask = true;
  const res = await postApi();
  btnLoading.orderTask = false;
  if (!res) return;
  RactionSheetRef.value.close();
  props.details.status = WkTaskStatus.ORDER_ACCEPT;
  props.details.task_order.status = WkTaskStatus.ORDER_ACCEPT;
  emit("orderTaskSuccess");
  /**请求api接口 */
  function postApi() {
    const task_id = props.details.id;
    const order_id = props.details.task_order.id;
    // 重新支付
    if (isPlayFailed.value)
      return apiOrderTaskRePlay({ order_id, txid: payRes.data! });
    return apiOrderTask({
      task_id,
      txid: payRes.data!,
    });
  }
}
const usdtAmount = computed(() => {
  /**佣金 */
  const commission = Number(props.details.commission);
  const task_setting = homeData.value?.task_setting;
  /**接单任务保证金比率 */
  const serveRatio = Number(task_setting?.order_task_earnest_money);
  return chain(serveRatio).multiply(0.01).multiply(commission).done();
});
const amount = computed(() => {
  const price = Number(WKC.value?.defaultPrice || homeData.value?.wkc.price);
  return divide(usdtAmount.value, price);
});
const isBadlyOff = computed(
  () => !(Number(WKC.value?.balance) >= Number(amount.value))
);
</script>
<template>
  <div class="auto-MT-md">
    <Ccard class="tips">
      <div class="flex-A-C">
        <Rimage
          size="32rem"
          :src="_require('src/assets/images/icon/checked.svg')"
        />
        <span class="ML-xs"> {{ $t("jie-dan-xu-zhi") }}</span>
      </div>
      <ul class="MT-md ML-sm C-T3">
        <li>
          {{ $t("xu-zai-gui-ding-shi-jian-nei-wan-cheng-suo-jie-ren-wu") }}
        </li>
        <li>{{ $t("jin-zhi-sui-yi-jie-dan") }}</li>
        <li>{{ $t("jin-zhieyi-ti-jiao") }}</li>
        <li>
          {{
            $t(
              "ru-ruo-wei-gui-dao-zhi-de-sun-shi-jiang-you-yong-hu-zhi-jie-cheng-dan"
            )
          }}
        </li>
      </ul>
    </Ccard>
    <div class="T-A-C C-fail T-S-sm">
      {{ $t("caoZuoSuoXuZiJinZhiFuChuCuoQingZhongXinZhiFu") }}
    </div>
    <Rbutton
      :loading="btnLoading.open"
      @click="open"
      bg="var(--C-LG1)" borderStyle="none"
      :size="'large'"
    >
      <span v-if="isPlayFailed">{{ $t("zhongXinZhiFu") }}</span>
      <span v-else>{{ $t("jie-dan-zhi-fu") }}</span>
    </Rbutton>

    <RactionSheet
      :close-on-click-overlay="!btnLoading.orderTask"
      ref="RactionSheetRef"
    >
      <VanDivider />
      <div class="PD-md">
        <div class="auto-MT-sm T-S-sm">
          <div class="flex-J-SB">
            <span class="C-T4">{{ $t("zhi-fu-dai-bi") }}</span>
            <span class="C-M1">
              {{ $t("yue") }}{{ fixedDecimals(WKC?.balance, 2) }}</span
            >
          </div>
          <Ccard class="PD-sm" bg="var(--C-B3)" border-style="none">
            <div class="flex-A-C flex-J-SB">
              <div>{{ fixedDecimals(amount, 4) }}</div>
              <div class="flex-A-C">
                <Rimage size="38rem" :src="WKC?.logo" />
                <span class="ML-xs">{{ WKC?.code }}</span>
              </div>
            </div>
          </Ccard>

          <Ccard class="PD-sm" bg="var(--C-B2)" border-style="none">
            <div class="flex-A-C flex-J-SB">
              <div class="C-T4">{{ $t("zhiFuJiaZhi") }}</div>
              <div>{{ fixedDecimals(usdtAmount, 2) }} USDT</div>
            </div>
          </Ccard>
          <Ccard class="PD-sm" bg="var(--C-B2)" border-style="none">
            <div class="flex-A-C flex-J-SB">
              <div class="C-T4">WKC/USDT</div>
              <div>
                {{ fixedDecimals(homeData?.wkc.price, 4) }}
              </div>
            </div>
          </Ccard>
          <Ccard class="PD-sm" bg="var(--C-B2)" border-style="none">
            <div class="flex-A-C">
              <Rimage
                size="38rem"
                :src="_require('src/assets/images/icon/checked.svg')"
              />
              <div class="ML-xs">{{ $t("zhongYaoTiShi") }}</div>
            </div>
            <div class="MT-xs C-T3">
              {{
                $t(
                  "ben-ci-zhi-fu-de-jinewei-ren-wu-lv-yue-bao-zheng-jin-ru-ruo-zai-gui-ding-shi-jian-nei-wan-cheng-ren-wu-bao-zheng-jin-jiang-sui-yong-jin-yi-bing-tui-hui-wei-an-shi-wan-cheng-huo-zhe-wei-gui-cao-zuo-zhe-bao-zheng-jin-jiang-bu-chang-gei-ci-ren-wu-fa-bu-zhe"
                )
              }}
            </div>
          </Ccard>
        </div>

        <div class="MT-md flex-J-SB" style="gap: var(--gap-md)">
          <Rbutton
            @click="RactionSheetRef?.close"
            :size="'large'"
            bg="var(--C-M1-O3)"
          >
            {{ $t("qu-xiao") }}
          </Rbutton>
          <!-- <Rbutton
            :loading="btnLoading.approve"
            @click="approve"
            v-if="isApprove"
            :size="'large'"
            bg="var(--C-LG1)" borderStyle="none"
          >
            {{ $t("pi-zhun") }}{{ WKC?.code }}
          </Rbutton> -->
          <Rbutton
            :loading="btnLoading.orderTask"
            :disabled="isBadlyOff"
            @click="orderTask"
            :size="'large'"
            bg="var(--C-LG1)" borderStyle="none"
          >
            <div v-if="isBadlyOff">
              {{ $t("yu-e-bu-zu") }}
            </div>
            <div v-else>{{ $t("que-reng-zhi-fu") }}</div>
          </Rbutton>
        </div>
      </div>
    </RactionSheet>
  </div>
</template>
<style lang="scss" scoped>
.tips {
  ul {
    list-style-type: "*";
  }
}
</style>
